const { ethers, run, network } = require("hardhat")

async function main() {
    const simpleStorageFactory =
        await ethers.getContractFactory("SimpleStorage")

    console.log("Deploying contract")

    const simpleStorage = await simpleStorageFactory.deploy()

    await simpleStorage.waitForDeployment()

    console.log(`Deploy contract to ${await simpleStorage.getAddress()}`)

    // console.log(network.config)

    if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY) {
        await simpleStorage.deploymentTransaction().wait(6)
        await verify(simpleStorage.getAddress(), [])
    }

    const currentValue = await simpleStorage.retrieve()
    console.log(`currentValue is ${currentValue}`)
    const deploymentTransaction = await simpleStorage.store(7)
    await deploymentTransaction.wait(1)
    const updatedValue = await simpleStorage.retrieve()
    console.log(`updatedValue is ${updatedValue}`)
}

async function verify(contractAddress, args) {
    console.log("Verifying contract...")
    try {
        await run("verify:verify", {
            address: contractAddress,
            constructorArgsParams: args,
        })
    } catch (e) {
        if (e.message.toLowerCase().includes("already verified")) {
            console.log("Already verified")
        } else {
            console.log(e)
        }
    }
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error)
        process.exit(1)
    })
